package com.yuexin.common.utils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 流水号生成工具
 */
public class SerialNoUtils {

    /**
     * 截取时间
     * @param time      需截取时间
     * @param pattern   截取时间格式，eg:需要年份后2位，pattern=“YY”
     * @return
     */
    public static String getTime(Date time, String pattern) {
        LocalDate localDate = dateToLocalDate(time);
        return localDate.format(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 数据前面补0
     * @param code     当前数据
     * @param num      数据长度
     * @return
     */
    public static String autoGenericCode(int code, int num) {
        return String.format("%0" + num + "d", code);
    }

    /**
     * Date 转 LocalDate
     *
     * @param date
     * @return
     */
    public static LocalDate dateToLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        return localDateTime.toLocalDate();
    }

    /**
     * 与当前时间相差天数
     *
     * @param time
     * @return
     */
    public static Long dateGap(Date time) {
        if (time == null) {
            return 0L;
        }
        LocalDate start = LocalDate.now();
        LocalDate end = SerialNoUtils.dateToLocalDate(time);
        return end.toEpochDay() - start.toEpochDay();
    }
}
